package com.tcc.naozhongservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.IBinder;
import android.os.Vibrator;

import com.tcc.datebase.MyDB;
import com.tcc.mynote.Base;

import java.util.Calendar;

public class SystemService extends Service {// 将所有闹钟在开机后重新设置一遍的服务

    private final String ALARM_ALERT_INTENT = "com.android.alarmclock.ALARM_ALERT";
    private final String AUDIO_INTENT = "com.android.alarmclock.AUDIO";
    public static Context context;
    AlarmManager am;
    private String strWeek;
    private String strWhichLesson;
    private String strName;
    private String strAddress;
    private String strPeriod;
    private String strStartTime;
    private String strEndTime;
    private String strRemindTime;
    private String strIsRemind;
    private String strIsRemindByVibrato;
    private String strIsRemindByRing;
    private String strTeacher;
    private String strSubmitDate;


    private static Vibrator vibrator = null;

    public static Vibrator getVibrator() {
        if (vibrator == null) {
            vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        }
        return vibrator;
    }

    private static AudioManager audioMgr = null;

    public static AudioManager getAudioMgr() {
        if (audioMgr == null)
            audioMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        return audioMgr;
    }


    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub

        super.onCreate();

        context = this;

        audioMgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        am = (AlarmManager) getSystemService(ALARM_SERVICE);


        MyDB db = new MyDB(this);
        Cursor cursor = db.queryAllCourses();
        Base base = new Base();
        int week;
        int alarmId;
        while (cursor.moveToNext()) {
            strWeek = cursor.getString(cursor.getColumnIndex("week"));
            strWhichLesson = cursor.getString(cursor.getColumnIndex("whichLesson"));
            strName = cursor.getString(cursor.getColumnIndex("cName"));
            strAddress = cursor.getString(cursor.getColumnIndex("address"));
            strPeriod = cursor.getString(cursor.getColumnIndex("period"));
            strStartTime = cursor.getString(cursor.getColumnIndex("startTime"));
            strEndTime = cursor.getString(cursor.getColumnIndex("endTime"));
            strRemindTime = cursor.getString(cursor.getColumnIndex("remindTime"));
            strIsRemind = cursor.getString(cursor.getColumnIndex("isRemind"));
            strIsRemindByVibrato = cursor.getString(cursor.getColumnIndex("isRemindByVibrato"));
            strIsRemindByRing = cursor.getString(cursor.getColumnIndex("isRemindByRing"));
            strTeacher = cursor.getString(cursor.getColumnIndex("teacher"));
            strSubmitDate = cursor.getString(cursor.getColumnIndex("submitDate"));

            int remindStartHour = Integer.parseInt(strRemindTime.split(":")[0]);
            int remindStartMinute = Integer.parseInt(strRemindTime.split(":")[1]);

            int startHour = Integer.parseInt(strStartTime.split(":")[0]);
            int startMinute = Integer.parseInt(strStartTime.split(":")[1]);
            int endHour = Integer.parseInt(strEndTime.split(":")[0]);
            int endMinute = Integer.parseInt(strEndTime.split(":")[1]);
            int aheadTime = 10;
            if (startMinute - remindStartMinute < 0) {
                aheadTime = 60 - remindStartMinute;
            } else {
                aheadTime = startMinute - remindStartMinute;
            }

            if (strIsRemind.equals("1")) {
                strIsRemind = "true";
            } else {
                strIsRemind = "false";
            }

            if (strIsRemindByVibrato.equals("1")) {
                strIsRemindByVibrato = "true";
            } else {
                strIsRemindByVibrato = "false";
            }

            if (strIsRemindByRing.equals("1")) {
                strIsRemindByRing = "true";
            } else {
                strIsRemindByRing = "false";
            }

            String[] strCurr = {strWeek, strWhichLesson, strName, strAddress, strStartTime, strEndTime, aheadTime + "", strIsRemind, strIsRemindByVibrato, strIsRemindByRing, strTeacher};

         	/*开机自启动服务把闹钟重新设置一遍*/

            // 星期三
            if (strWeek.equals("三") && strWhichLesson.equals("1-2")) {
                if (strIsRemind.equals("true") || (strIsRemind.equals("true") && strIsRemindByVibrato.equals("true") && strIsRemindByRing.equals("false")) || (strIsRemind.equals("true") && strIsRemindByVibrato.equals("false") && strIsRemindByRing.equals("true"))) {
                    week = base.changeStrWeekToInt(strWeek);
                    alarmId = base.getAlarmId(week, strWhichLesson);
                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + alarmId);
                    setAlarmAndAudio(alarmId, week, strCurr, Integer.parseInt(strPeriod), base.formateTime(remindStartHour), base.formateTime(remindStartMinute), base.formateTime(startHour), base.formateTime(startMinute), base.formateTime(endHour), base.formateTime(endMinute));
                }
            }
        }
    }


    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    // 设置提醒闹钟和情景模式
    public void setAlarmAndAudio(int alarmId, int week, String[] strCurr, int period, String remindStartHour, String remindStartMinute, String startHour, String startMinute, String endHour, String endMinute) {

        int remindHour = Integer.parseInt(remindStartHour);
        int remindMinute = Integer.parseInt(remindStartMinute);

        int mode = audioMgr.getRingerMode();
        System.out.println("mode:" + mode);

        int audioStartHour = Integer.parseInt(startHour);
        int audioStartMinute = Integer.parseInt(startMinute);
        int audioEndHour = Integer.parseInt(endHour);
        int audioEndMinute = Integer.parseInt(endMinute);

        // 当前时间
        Calendar nowCalendar = Calendar.getInstance();
        nowCalendar.setTimeInMillis(System.currentTimeMillis());

        Calendar remindCalendar = Calendar.getInstance();

        // 设置的提醒时间
        remindCalendar.setTimeInMillis(System.currentTimeMillis());
        remindCalendar.set(Calendar.HOUR_OF_DAY, remindHour);
        remindCalendar.set(Calendar.MINUTE, remindMinute);
        remindCalendar.set(Calendar.DAY_OF_WEEK, week);
        remindCalendar.set(Calendar.SECOND, 0);
        remindCalendar.set(Calendar.MILLISECOND, 0);

        System.out.println(remindCalendar.get(Calendar.HOUR_OF_DAY));
        System.out.println(remindCalendar.get(Calendar.MINUTE));

        Intent remindIntent = new Intent(ALARM_ALERT_INTENT);
        remindIntent.putExtra("cInfo", strCurr);
        PendingIntent remindSender = PendingIntent.getBroadcast(this, alarmId, remindIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        long remindStartTimeInMillis = remindCalendar.getTimeInMillis();
        long remindPeriod = 7 * 24 * 60 * 60 * 1000;// 提醒周期初始化为一个星期的时间毫秒数

        // 启动时间
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTimeInMillis(System.currentTimeMillis());
        startCalendar.set(Calendar.HOUR_OF_DAY, audioStartHour);
        startCalendar.set(Calendar.MINUTE, audioStartMinute);
        startCalendar.set(Calendar.DAY_OF_WEEK, week);
        startCalendar.set(Calendar.SECOND, 0);
        startCalendar.set(Calendar.MILLISECOND, 0);

        // 结束时间
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTimeInMillis(System.currentTimeMillis());
        endCalendar.set(Calendar.HOUR_OF_DAY, audioEndHour);
        endCalendar.set(Calendar.MINUTE, audioEndMinute);
        endCalendar.set(Calendar.DAY_OF_WEEK, week);
        endCalendar.set(Calendar.SECOND, 0);
        endCalendar.set(Calendar.MILLISECOND, 0);

        Intent startIntent = new Intent(AUDIO_INTENT);
        startIntent.putExtra("audioMode", mode + "");
        startIntent.putExtra("audioSituation", "start");
        PendingIntent startSender = PendingIntent.getBroadcast(this, alarmId + 100, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent endIntent = new Intent(AUDIO_INTENT);
        endIntent.putExtra("audioMode", mode + "");
        endIntent.putExtra("audioSituation", "end");
        PendingIntent endSender = PendingIntent.getBroadcast(this, alarmId + 100 + 100, endIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        long audioStartTimeInMillis = startCalendar.getTimeInMillis();
        long audioEndTimeInMillis = endCalendar.getTimeInMillis();
        long audioPeriod = 7 * 24 * 60 * 60 * 1000;// 提醒周期初始化为一个星期的时间毫秒数

        // 当前时间 比 设置的提醒时间 要后 的时候。（比如设置提醒的时间为星期一的9:00，提交时的当前时间为星期二的9:00的时候）
        if (nowCalendar.after(remindCalendar)) {
            if (period == 0) {// 单双周
                remindStartTimeInMillis = remindStartTimeInMillis + remindPeriod;// 下个星期的毫秒数
                audioStartTimeInMillis = audioStartTimeInMillis + audioPeriod;//
                audioEndTimeInMillis = audioEndTimeInMillis + audioPeriod;//
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, remindPeriod, remindSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, audioPeriod, endSender);
                System.out.println("a");
            } else if (period == 11 || period == 22) {// 目前单周，设置了单周的课程，或目前双周，设置了双周的课程
                if (isSetAlarm(period, strSubmitDate)) {
                    remindStartTimeInMillis = remindStartTimeInMillis + 2 * remindPeriod;
                    if (nowCalendar.before(endCalendar)) {
                        System.out.println("b1");
                    } else {
                        audioStartTimeInMillis = audioStartTimeInMillis + 2 * audioPeriod;//
                        audioEndTimeInMillis = audioEndTimeInMillis + 2 * audioPeriod;//
                        System.out.println("b2");
                    }
                } else {
                    remindStartTimeInMillis = remindStartTimeInMillis + remindPeriod;
                    audioStartTimeInMillis = audioStartTimeInMillis + audioPeriod;//
                    audioEndTimeInMillis = audioEndTimeInMillis + audioPeriod;//
                    System.out.println("c");
                }
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, remindPeriod, remindSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, audioPeriod, endSender);
            } else if (period == 12 || period == 21) {// 目前单周，设置了双周的课程，或目前双周，设置了单周的课程
                if (isSetAlarm(period, strSubmitDate)) {
                    remindStartTimeInMillis = remindStartTimeInMillis + 2 * remindPeriod;
                    if (nowCalendar.before(endCalendar)) {
                        System.out.println("d1");
                    } else {
                        audioStartTimeInMillis = audioStartTimeInMillis + 2 * audioPeriod;//
                        audioEndTimeInMillis = audioEndTimeInMillis + 2 * audioPeriod;//
                        System.out.println("d2");
                    }
                } else {
                    remindStartTimeInMillis = remindStartTimeInMillis + remindPeriod;
                    audioStartTimeInMillis = audioStartTimeInMillis + audioPeriod;//
                    audioEndTimeInMillis = audioEndTimeInMillis + audioPeriod;//
                    System.out.println("e");
                }
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, 2 * remindPeriod, remindSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, 2 * audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, 2 * audioPeriod, endSender);
            }
        } else {
            if (period == 0) {// 单双周
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, remindPeriod, remindSender);// 开始时间为这个星期的某个时间，一星期提醒一次
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, audioPeriod, endSender);
                System.out.println("f");
            } else if (period == 11 || period == 22) {// 目前单周，设置了单周的课程，或目前双周，设置了双周的课程
                if (isSetAlarm(period, strSubmitDate)) {
                    System.out.println("g");
                } else {
                    remindStartTimeInMillis = remindStartTimeInMillis + remindPeriod;
                    audioStartTimeInMillis = audioStartTimeInMillis + audioPeriod;//
                    audioEndTimeInMillis = audioEndTimeInMillis + audioPeriod;//
                    System.out.println("h");
                }
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, 2 * remindPeriod, remindSender);// 开始时间为这个星期的某个时间，两星期提醒一次
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, 2 * audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, 2 * audioPeriod, endSender);
            } else if (period == 12 || period == 21) {// 目前单周，设置了双周的课程，或目前双周，设置了单周的课程
                if (isSetAlarm(period, strSubmitDate)) {
                    System.out.println("i");
                } else {
                    remindStartTimeInMillis = remindStartTimeInMillis + remindPeriod;
                    audioStartTimeInMillis = audioStartTimeInMillis + audioPeriod;//
                    audioEndTimeInMillis = audioEndTimeInMillis + audioPeriod;//
                    System.out.println("j");
                }
                am.setRepeating(AlarmManager.RTC_WAKEUP, remindStartTimeInMillis, 2 * remindPeriod, remindSender);// 开始时间为下星期的某个时间，两星期提醒一次
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioStartTimeInMillis, 2 * audioPeriod, startSender);
                am.setRepeating(AlarmManager.RTC_WAKEUP, audioEndTimeInMillis, 2 * audioPeriod, endSender);
            }
        }
    }


    public boolean isSetAlarm(int period, String submitDate) {
        boolean flag = false;
        int year = Integer.parseInt(submitDate.split("-")[0]);
        int month = Integer.parseInt(submitDate.split("-")[1]);
        int day = Integer.parseInt(submitDate.split("-")[2]);

        Calendar c = Calendar.getInstance();
        c.set(year, month - 1, day);
        Calendar now = Calendar.getInstance();
        long interval = Math.abs((now.getTimeInMillis() - c.getTimeInMillis()) / (1000 * 3600 * 24));
//    	System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~" + interval);
        System.out.println(now.get(Calendar.YEAR));
        System.out.println(now.get(Calendar.MARCH) + 1);
        System.out.println(now.get(Calendar.DAY_OF_MONTH));

        if (period == 11 || period == 22) {
            if ((interval / 7) % 2 == 0) {
                flag = true;
                System.out.println("11" + "&&22" + flag);
            } else if ((interval / 7) % 2 == 1) {
                flag = false;
                System.out.println("11" + "&&22" + flag);
            }
        } else if (period == 12 || period == 21) {
            if ((interval / 7) % 2 == 0) {
                flag = false;
                System.out.println("12" + "&&21" + flag);
            } else if ((interval / 7) % 2 == 1) {
                flag = true;
                System.out.println("12" + "&&21" + flag);
            }
        }

        return flag;
    }

    // 取消提醒闹铃
    public void cancelAlarm(int alarmId) {
        Intent intent = new Intent(ALARM_ALERT_INTENT);
        PendingIntent sender = PendingIntent.getBroadcast(this, alarmId, intent, 0);
        // 由AlarmManager中删除 *
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(sender);
    }
}
